import { insertCart, findCartList, deleteCart, updateCart, checkAllCart } from '@/api/cart.js'

// 购物车模块
const cart = {
  namespaced: true,
  state: () => ({
    list: [] // 购物车列表
  }),
  mutations: {
    getListFn (state, data) {
      state.list = data
    },
    // 重新登录其他用户,更新购物车
    updateFn (state, data) {
      state.list = data
    }
  },
  actions: {
    // 获取登录后的购物车列表
    async asyncList (store, { skuId, count }) {
      await insertCart({ skuId, count })
      // 调用获取购物车列表接口
      const res = await findCartList()
      // console.log(res.data.result)
      store.commit('getListFn', res.data.result)
    },
    // 删除skuId组成的数组
    async asyncdeleteFn (store, ids) {
      await deleteCart(ids)
      // 需要重新获取最新列表数据,刷新页面
      const res = await findCartList()
      store.commit('getListFn', res.data.result)
    },
    // 重新登录时,更新购物车信息
    async updateCartList (store) {
      const res = await findCartList()
      store.commit('getListFn', res.data.result)
    },
    // 修改单选框的状态,保存到数据库中
    async updateRadio (store, goods) {
      await updateCart(goods)
      const res = await findCartList()
      store.commit('getListFn', res.data.result)
    },
    // 改变全选框状态的函数
    async updateCheckBox (store, selected) {
      await checkAllCart({ selected, ids: store.state.list.map(item => item.skuId) })
      const res = await findCartList()
      store.commit('getListFn', res.data.result)
    }
  },
  getters: {
    // 当数据变量依赖state中的数据计算得到时,就要用到getters计算
    price (state) { // 总价钱
      return state.list.reduce((sum, obj) => {
        return sum + obj.count * obj.price
      }, 0)
    },
    // 总个数
    total (state) {
      // eslint-disable-next-line no-return-assign
      return state.list.reduce((sum, obj) => sum += obj.count, 0)
    },
    // 计算选中项钱数的总和
    prices (state) {
      return state.list.filter(item => item.selected).reduce((sum, obj) => sum + obj.count * obj.nowOriginalPrice, 0)
    },
    // 计算出selected为true的值,将他们的个数进行相加
    totalTrue (state) {
      return state.list.filter(item => item.selected).reduce((sum, obj) => sum + obj.count, 0)
    },
    // 小选都选中改变大选
    smallSelection (state) {
      return state.list.every(item => item.selected === true)
    }

  }
}

export default cart
